import json

import  requests
import os
class TComm:
    def __init__(self):
        self.dbs={}
    def registDB(self, dbKey, host,port,db,token, sqlRootPath):
        try:
            self.dbs[dbKey]={
                "host":host,
                "port":port,
                "db":db,
                "token":token,
                "sqlRootPath":sqlRootPath
            }
        except Exception as er:
            print(er)
    def getSql(self, sqlRootPath ,sqlKey):
        res = ""
        try:
            filePath = os.path.join(sqlRootPath, sqlKey)
            if filePath.find(".txt") < 0:
                filePath = filePath + ".txt"
            if os.path.exists(filePath):
                with open(filePath, "r", encoding='utf-8') as f:
                    res = f.read()
            else:
                print('sqlKey(' + sqlKey + ') is error.')
        except Exception as er:
            print(er)
        return res
    def query(self , dbKey , sqlPath , params , action = 'query'):
        res = {"status":0 , "queryResult":None}
        try:
            if dbKey in self.dbs.keys():
                dbInfo = self.dbs[dbKey]
                sql = self.getSql(dbInfo['sqlRootPath'], sqlPath)
                if params!=None :
                    for k in params.keys():
                        sql = sql.replace('%('+k+')s', str(params[k]))
                tdbHost = dbInfo['host']
                tdbPort = dbInfo['port']
                tdbDB = dbInfo['db']
                tdbToken = dbInfo['token']
                try:
                    res['queryResult'] = json.loads ((TComm.queryInfluxData(tdbHost , tdbPort , tdbDB , tdbToken , sql , action)).text)
                    res['status'] = 1
                except Exception as eer:
                    print(eer)
        except Exception as er:
            print(er)
        return  res
    def postBatchDatapoints(self , dbKey , datapoints ):
        res = {"status":0 , "queryResult":None}
        try:
            if dbKey in self.dbs.keys():
                dbInfo = self.dbs[dbKey]
                tdbHost = dbInfo['host']
                tdbPort = dbInfo['port']
                tdbDB = dbInfo['db']
                tdbToken = dbInfo['token']
                try:
                    postRes = TComm.postInflux(tdbHost , tdbPort , tdbDB , tdbToken , datapoints)
                    if postRes.text =="" :
                        res['postResult'] = 'OK'
                    else:
                        res['postResult'] = json.loads (postRes.text)
                    res['status'] = 1
                except Exception as eer:
                    print(eer)
        except Exception as er:
            print(er)
        return  res

    def webQuery(self , result , params , request):
        try:
            dbKey = ""
            sqlPath = ""
            action='query'
            ps ={}
            for k , v in params.items():
                if "dbKey_" ==k:
                    dbKey = v
                elif "dbPath_" == k :
                    sqlPath = v
                elif "action_" == k :
                    action = v
                else:
                    ps[k] = v
            if dbKey in self.dbs.keys():
                rs = self.query(dbKey , sqlPath, ps , action)
                result["result"] = rs
            else:
                result["error"]['code'] = -10
                result["error"]['message'] = "dbKey is error."
        except Exception as er:
            print(er)
    def webPostBatchDatapoints(self , result , params , request):
        try:
            dbKey = ""
            datapoints = ""
            ps ={}
            for k , v in params.items():
                if "dbKey_" ==k:
                    dbKey = v
                else:
                    ps[k] = v
            if dbKey in self.dbs.keys():
                datapoints = ps['dps']
                rs = self.postBatchDatapoints(dbKey , datapoints )
                result["result"] = rs
            else:
                result["error"]['code'] = -10
                result["error"]['message'] = "dbKey is error."
        except Exception as er:
            print(er)

    @staticmethod
    def getDatapointStr( tabName , tags , fields):
        res = ""
        try:
            dataStrs = tabName
            tagArray = []
            for tk,tv in tags.items():
                t = tk +"="+str(tv)
                tagArray.append(t)
            dataStrs = dataStrs +"," + ",".join(tagArray)
            fieldArray = []
            for fk ,fv in  fields.items():
                f = fk+"="+str(fv)
                fieldArray.append(f)
            dataStrs = dataStrs +" "+",".join(f)
            res = dataStrs
        except Exception as er:
            print(er)
        return  res
    @staticmethod
    def postInflux( host , port , db ,  token , datapointStr, repolyicy=''):
        resp = None
        try:
            headers = {
                "Authorization": token,
                'Content-Type': 'application/json',
            }
            influxdb_url = "http://" + host + ":" + str(port) + '/write?db=' + db
            if repolyicy!='':
               influxdb_url = influxdb_url + '&rp='+repolyicy
            resp = requests.post(url=influxdb_url, headers=headers, data=datapointStr)

        except Exception as er:
            print(er)
        return  resp
    @staticmethod
    def save2Influx( host , port , db ,  token , tabName , tags , fields, repolyicy=''):
        resp = None
        try:
            dataStr = TComm.getDatapointStr(tabName , tags , fields)
            resp = TComm.postInflux(host , port , db , token , dataStr , repolyicy)
        except Exception as er:
            print(er)
        return  resp
    @staticmethod
    def queryInflux( host , port , db ,  token , sql , action="write"):
        resp = None
        try:
            headers = {
                "Authorization": token,
                'Content-Type': 'application/json',
            }
            influxdb_url = "http://" + host + ":" + str(port) + '/'+action+'?db=' + db
            ps={
                "q": sql
            }
            resp = requests.post(url=influxdb_url, headers=headers, data=ps)

        except Exception as er:
            print(er)
        return  resp
    @staticmethod
    def queryInfluxData( host , port , db ,  token , sql , action="write"):
        resp = None
        try:
            headers = {
                "Authorization": token,
                'Content-Type': 'application/json',
            }
            influxdb_url = "http://" + host + ":" + str(port) + '/'+action+'?db=' + db
            influxdb_url = influxdb_url +"&q="+sql
            resp = requests.post(url=influxdb_url, headers=headers )
            print(resp)
        except Exception as er:
            print(er)
        return  resp

comm = TComm()